import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio/dio.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:my_flutter/core/Environment.dart';
import 'DioEx.dart';
import 'interceptor/ApiInterceptor.dart';


class DioManager {
  Dio dio = Dio();
  static final CookieJar cookieJar = CookieJar();
  static DioManager? _instance;

  static DioManager getInstance() {
    if (_instance == null) {
      _instance = DioManager();
      _instance!._init();
    }
    return _instance!;
  }

  void _init() {
    dio.options.connectTimeout = 10000;
    dio.options.receiveTimeout = 10000;
    //响应的数据类型
    dio.options.responseType = ResponseType.json;
    //请求的contentType
    dio.options.contentType = "application/x-www-form-urlencoded";
    //网络请求的baseUrl：https://www.wanandroid.com/
    dio.options.baseUrl = Environment.baseUrl;
    dio.interceptors.add(ApiInterceptor()); //请求拦截器
    //cookie
    dio.interceptors.add(CookieManager(cookieJar));
  }
  //设置baseUrl
  void setBaseUrl(String baseUrl) {
    dio.options.baseUrl = baseUrl;
  }

  //原生开发，通过header添加cookie
  void setHeader(Map<String, String>? headers) {
    dio.options.headers = headers;
  }

  ///post json
  Future post(String path, {Map<String, dynamic>? params, bool withLoading = true,}) async {
    //添加 tag（用以web开发，本地代理转发）
    if(Environment.enumValue == EnvironmentEnum.web_dev) {
      path = Environment.tag + path;
    }
    try {
      Response response = await dio.post(path, data: params);
      return handleResponse(response);
    } on DioError catch (e) {
      return handleFailed(e.response);
    }
  }


  ///get
  Future get<T>(String path, {Map<String, dynamic>? params, bool withLoading = true,}) async {
    //添加 tag（用以web开发，本地代理转发）
    if(Environment.enumValue == EnvironmentEnum.web_dev) {
      path = Environment.tag + path;
    }
    try {
      Response response = await dio.get(path, queryParameters: params);
      return handleResponse(response);
    } on DioError catch (e) {
      return handleFailed(e.response);
    }
  }

  //处理成功的数据
  Future handleResponse(Response response) {
    RespData respData = RespData.fromJson(response.data);
    if(respData.data == null) {
      return handleFailed(response);
    }
    //取出response.data.data，并返回
    return Future.value(respData.data);
  }

  // 处理失败的数据
  Future handleFailed(Response? response) {
    debugPrint('---api-resp---->error------>$response');
    //response.data 转换为 RespData，并返回
    var map = RespData.fromJson(response?.data);
    return Future.value(map);
  }
}
